<?php
namespace app\admin\controller;
use app\admin\model\Shijuan as ShijuanModel;
use think\facade\Request;
use app\admin\traits\Result;
use think\validate;
use think\Db;
use Mpdf\Mpdf;

class Shijuan extends Common
{
    
    public function index(){
        if ($this->request->isAjax()) {
            $data = [
                'key' => $this->request->get('key', '', 'trim'),
                'limit' => $this->request->get('limit', 10, 'intval'),
            ];

            $order_name = empty($this->request->get('field')) ?'s_id':$this->request->get('field');
            $order_type = empty($this->request->get('order')) ?'desc':$this->request->get('order');
            
            $list = ShijuanModel::withSearch(['title'], ['title' => $data['key']])->order($order_name.' '.$order_type)//->order('s_id desc')
                ->paginate($data['limit'], false, ['query' => $data]);
               // dump(ShijuanModel::getlastsql());die;
            $user_date = [];
            foreach ($list as $key => $val) {
                $user_date[$key] = $val;
                //$user_date[$key]['typetitle'] = $val->typetitle;
            }
            return show($user_date, 0, '', ['count' => $list->total()]);
        }
        return $this->fetch();
        
    }

     
    
    public function edit(){
       if ($this->request->isPost()) {
            $data = $this->request->post();
			
			$validate = validate('Shijuan');
			if (!$validate->check($data)) {
				//令牌数据无效时重置令牌
				$validate->getError() != '令牌数据无效' ? $token = Request::token() : $token = '';
				$msg = Result::error($validate->getError(), null, ['token' => $token]);
				return $msg;
			}
				
            if ($data['s_id']) {
				$data['update_time'] = time();
                //编辑
                $res = ShijuanModel::update($data, ['id' => $data['s_id']]);
                if ($res) {
                    $msg = Result::success('编辑成功', url('/admin/shijuan-list'));
                } else {
                    $msg = Result::error('编辑失败');
                }
            } else {
                //添加
                $ShijuanModel = new ShijuanModel;
				$data['create_time'] = time();
                $res = $ShijuanModel->allowField(true)->save($data);
                if ($res) {
                    $msg = Result::success('添加成功', url('/admin/shijuan-list'));
                } else {
                    $msg = Result::error('添加失败');
                }
            }
            return $msg;
        } else {
           $s_id = $this->request->get('s_id', 0, 'intval');
            if ($s_id) {
                $list = ShijuanModel::where('s_id', '=', $s_id)->find();
                $this->assign('list', $list);
            }

            return $this->fetch();
        } 
        
    }
    
    
    public function del(){
        $s_id = $this->request->param('s_id', 0, 'intval');
        if ($s_id) {
                $res = ShijuanModel::where('s_id='.$s_id)->delete();
                if ($res) {
                    $msg = Result::success('删除成功');
                } else {
                    $msg = Result::error('删除失败');
                }
        
                return $msg;
            
        } else {
            $this->error('参数错误');
        }
        
    }

    public function manage()
    {
        $s_id = $this->request->param('s_id', 0, 'intval');
        if (!$s_id) {
            $this->error('参数错误');
        }
        $ShijuanInfo = Db::name('Shijuan')->where('s_id',$s_id)->field('title,info')->find();
        $questions_arr = json_decode($ShijuanInfo['info'],true)??[];
        $questions_ids_arr = [];
        $shijuanInfo_sort = [];
        foreach ($questions_arr as $k=>$v) {
            $questions_ids_arr[] = $v['id'];
            $shijuanInfo_sort[$v['id']] = $v;
        }
        $list = db::name('questions')->where(['status'=>1])->where('id','in',$questions_ids_arr)->select();
        foreach($list as $k=>$v){
            $list[$k]['sort'] = $shijuanInfo_sort[$v['id']]['sort'];
        }
        $list = array_values(array_sort($list,'sort','asc'));
        $this->assign('list',$list);
        $this->assign('s_id',$s_id);
        $this->assign('title',$ShijuanInfo['title']);
        return $this->fetch();
    }

    public function manageedit(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data['s_id']) {
                $this->error('参数错误');
            }
            $ShijuanInfo = Db::name('Shijuan')->where('s_id',$data['s_id'])->field('title,info')->find();
            if(empty($ShijuanInfo)){
                $msg = Result::error('没有此试卷');
                return $msg;
            }
            //dump($data);die;
            $info = json_encode($data['info'],JSON_UNESCAPED_UNICODE);
            $res = Db::name('Shijuan')->where('s_id',$data['s_id'])->update(['info'=>$info,'update_time'=>time()]);
            if ($res) {
                $msg = Result::success('操作成功',url('/admin/shijuan-manage',['s_id'=>$data['s_id']]));
            } else {
                $msg = Result::error('操作失败');
            }
            return $msg;
        }
    }
	
	
	public function managesort(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data['s_id']) {
                $this->error('参数错误');
            }
            $ShijuanInfo = Db::name('Shijuan')->where('s_id',$data['s_id'])->field('title,info')->find();
            if(empty($ShijuanInfo)){
                $msg = Result::error('没有此试卷');
                return $msg;
            }
            
			foreach($data['info'] as $k=>$v){
				$data['info'][$k]['id']=$v['id'];
				$data['info'][$k]['sort']=$k;
			}
            $info = json_encode($data['info'],JSON_UNESCAPED_UNICODE);
            $res = Db::name('Shijuan')->where('s_id',$data['s_id'])->update(['info'=>$info,'update_time'=>time()]);
            if ($res) {
                $msg = Result::success('操作成功',url('/admin/shijuan-manage',['s_id'=>$data['s_id']]));
            } else {
                $msg = Result::error('操作失败');
            }
            return $msg;
        }
    }
	
    public function managedel()
    {

        $s_id = $this->request->param('s_id', 0, 'intval');
        $id = $this->request->param('id', 0, 'intval');
        if (!$s_id || !$id) {
            $this->error('参数错误');
        }
        $info = Db::name('Shijuan')->where('s_id',$s_id)->value('info');
        $questions_arr = json_decode($info,true);
        foreach ($questions_arr as $k=>$v){
            if($v['id'] == $id){
                unset($questions_arr[$k]);
            }
        }
        $questions_arr = array_values($questions_arr);
        $info = json_encode($questions_arr,JSON_UNESCAPED_UNICODE);
        //dump($questions_arr);die;
        $res = Db::name('Shijuan')->where('s_id',$s_id)->update(['info'=>$info,'update_time'=>time()]);
        if ($res) {
            $msg = Result::success('操作成功');
        } else {
            $msg = Result::error('操作失败');
        }
        return $msg;
    }

    //清空
	public function delall()
    {
        $res = Db::name('Shijuan')->delete(true);
        if ($res) {
            $msg = Result::success('操作成功');
        } else {
            $msg = Result::error('操作失败');
        }
        return $msg;
    }
    
}



?>